/*
 * led_function.h
 *
 *  Created on: 2010-12-16
 *      Author: minfang
 */

#ifndef LED_FUNCTION_H_
#define LED_FUNCTION_H_


#define LED_DATA_PORT PORTC
#define LED_DATA_DDR  DDRC

#define LED_SELECT_PORT PORTD
#define LED_SELECT_DDR  DDRD

#define LED1 5
#define LED2 6
#define LED3 7


// 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
const unsigned char number_table[] = { 0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92,
		0x82, 0xF8, 0x80, 0x90, 0x88, 0x83, 0xc6, 0xa1, 0x86, 0x8e, 0xff };

// for three led
char show_buffer_led[24];
char show_buffer_index[24];

unsigned char show_max;
unsigned char show_current;

char enable_led;

void turn_off_all_led(void) {
	// turn off all led;

	LED_SELECT_PORT &= ~(1 << LED1 | 1 << LED2 | 1 << LED3); // turn off all led
	LED_DATA_PORT = 0xFF;

}

void init_led(void) {
	// set led selector port is output
	LED_SELECT_DDR |= 1 << LED1 | 1 << LED2 | 1 << LED3;
	// set led control port is output
	LED_DATA_DDR = 0xFF;

	show_max = 0;
	turn_off_all_led();

}

char set_led_buffer(char index, char start, char number, char point) {
	char i1;

	if (number < 0 || number > 16) {
		number = 16;
	}
	const unsigned char cc = number_table[(int) number];

	for (i1 = 0; i1 < 7; i1++) {
		if ((cc & 1 << i1) == 0) {

			show_buffer_led[(int) start] = i1;
			show_buffer_index[(int) start] = index;
			start++;
		}
	}

	if (point) {
		show_buffer_led[(int) start] = 7;
		show_buffer_index[(int) start] = index;
		start++;
	}

	return start;

}

void led_show(char number1, char point1, char number2, char point2,
		char number3, char point3) {

	show_max = 0;

	show_max = set_led_buffer(LED3, show_max, number3, point3);

	show_max = set_led_buffer(LED2, show_max, number2, point2);

	show_max = set_led_buffer(LED1, show_max, number1, point1);

	enable_led = 1;

}

void led_process() {
	if (show_current >= show_max) {
		show_current = 0;
	}

	turn_off_all_led();

	//every time only show one led (not the whole number, only one of eight piece).

	LED_DATA_PORT = ~(1 << show_buffer_led[show_current]);

	LED_SELECT_PORT |= (1 << show_buffer_index[show_current]); //turn on the led

	show_current++;
}

#endif /* LED_FUNCTION_H_ */
